package cn.jekun.shop.app.action;

import javax.annotation.Resource;

import net.sf.json.JSONObject;
import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.shop.common.service.UpdateService;


/**
 * 手机apk版本
 * @author yuanhw
 *
 */
@SuppressWarnings("serial")
public class UpdateAction extends AppBaseAction{
	
	@Resource(name = UpdateService.BEAN_NAME)
	UpdateService updateService;
	
	/**
	 * 获取手机apk版本信息
	 * @return
	 */
	public String getVersion(){
		JSONObject jsonObject = null;
		try{
			jsonObject = this.updateService.getVersion();
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}
	
	/**
	 * 下载最新的apk
	 * @return
	 */
	public String download(){
		JSONObject jsonObject = null;
		try{
			String from = request.getParameter("from");
			String shopId = request.getParameter("shopId");
			String userId = request.getParameter("userId");
			jsonObject = this.updateService.getVersion();
			
			String version = jsonObject.getString("version");//服务端APK的版本（Int）
			String apkName = jsonObject.getString("apkName");//服务端APK的名称
			String apkUrl = jsonObject.getString("apkUrl");//服务端APK的下载地址
			//String memo = jsonObject.getString("memo");//服务端升级版本信息
			String agent = request.getHeader("USER-AGENT");//
			String memo = (from==null?"":from)+"下载app。版本："+version +",名称："+apkName+(shopId==null?"":",邀请商家代码："+shopId)+(userId==null?"":",邀请用户代码："+userId)  +"."+agent;
			this.logService.addAppDownloadLog("", this.getBrowser(), this.getIp(), memo.length()>400?memo.substring(0, 400):memo);
			
			return this.writeHtmlScript("<script>top.location='http://www.storeme.cn/file/d/"+apkUrl+"';</script>");
			//this.response.sendRedirect("http://www.storeme.cn/file/d/"+apkUrl); 会进入2次
			//return "!http://www.storeme.cn/file/d/"+apkUrl; 会进入2次
			
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
		}
		
		return null;
	}
}
